package librus.cheeseChaser.screens
{
	import com.greensock.TweenLite;
	
	import flash.geom.Point;
	
	import librus.cheeseChaser.components.Mat;
	import librus.cheeseChaser.components.MatControl;
	import librus.cheeseChaser.events.MoveEvent;
	import librus.cheeseChaser.tile.DeckCreator;
	import librus.cheeseChaser.tile.Tile;
	import librus.cheeseChaser.tile.TileType;
	import librus.cheeseChaser.util.Sprite;
	
	public class InGame extends Sprite
	{
		public function InGame()
		{
			super();
		}
				
		private var deck:Array;
		private var model:MatControl;
		private var mat:Mat;
		
		
		override protected function startup():void
		{					
			isListeningToResize = true;
											
			mat = new Mat;
			addChild(mat);			
			
			model = new MatControl(mat);
			model.addEventListener(MoveEvent.MOVE_SELECTED, onMoveSelected);
			
			createDeck();
			
			onResize();
			moveItemToHolder();	
		}
		
		private function onMoveSelected(event:MoveEvent):void
		{
			moveItemToHolder(event.position, event.modelPosition);
		}
		
		private function createDeck():void
		{
			deck = (new DeckCreator).getNewDeck();
			
			var item:Tile;
			for (var i:int=0;i<deck.length;i++)
			{
				item= deck[i] as Tile;
				item.y = (deck.length - i)*5;
				addChild(item);				
			}
			item.flip();
		}
		
		private function moveItemToHolder(position:Point=null, modelPosition:Point=null):void
		{	
			if (!deck.length) return;
			var item:Tile = deck[deck.length -1] as Tile;
			
			if (!position)
				position = new Point(mat.x + (mat.width - item.width)/2, mat.y +(mat.height-item.height)/2);
			if (!modelPosition)
				modelPosition = new Point(0,0);
			
			model.addTile(item,modelPosition);
						
			TweenLite.to(item,0.3,{x:position.x, y:position.y, onComplete:onTween});
		}
		
		private function onTween():void
		{
			var item:Tile = deck.pop() as Tile;
			var position:Point = localToGlobal(new Point(item.x, item.y));
			
			removeChild(item);
			mat.addTile(item, position);
			
			model.drawPossibleMoves(item);
			model.countPoints();
			
			item = deck[deck.length-1] as Tile;
			item.flip();			
		}
		
		override protected function onResize():void
		{
			var firstTile:Tile = deck[deck.length-1] as Tile;
			mat.x = firstTile.x + firstTile.width + 10;
			mat.y = 0;
			mat.width = stage.stageWidth - mat.x;
			mat.height = stage.stageHeight;				
		}
	}
}